package com.hs.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hs.entity.dto.MessageDTO;
import com.hs.entity.pojo.Message;
import com.hs.mapper.MessageMapper;
import com.hs.service.MessageService;
import com.hs.utils.BeanCopyUtil;
import com.hs.utils.RedisCache;
import com.hs.utils.ResultResponse;
import com.hs.utils.SecurityUserHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hs
 * @since 2023-08-05
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Resource
    private RedisCache redisCache;

    @Override
    public ResultResponse<?> saveMessage(MessageDTO messageDTO) {
        Message message = BeanCopyUtil.copyBean(messageDTO, Message.class);

        // 用于redis查询消息标识
        Integer dialogueId = message.getDialogueId();

        setInRedis(message, dialogueId);

        return ResultResponse.ok();
    }

    private synchronized void setInRedis(Message message, Integer dialogueId) {
        List<Message> messageList = redisCache.getCacheList("pet:view:dialogue:" + dialogueId);
        // 说明redis中没有该对话的消息，则咱们创建一个
        if (Objects.isNull(messageList)){
            messageList = new ArrayList<>();
        }

        messageList.add(message);
        // 再存入redis
        // TODO 需优化 傻逼行为
        redisCache.deleteObject("pet:view:dialogue:" + dialogueId);
        List<Message> messages = messageList.stream().distinct().collect(Collectors.toList());
        redisCache.setCacheList("pet:view:dialogue:" + dialogueId,messages);
    }

    @Override
    public ResultResponse<List<Message>> getMessageByDialogueId(Integer dialogueId) {
        List<Message> messageList = redisCache.getCacheList("pet:view:dialogue:" + dialogueId);

        // 当前用户ID
        Integer userId = SecurityUserHolder.getUserId();
        // 将用户消息设置成已读
        messageList.forEach(message -> {
            // 说明我是接收方，则把消息设置为已读
            if (message.getMessageReceiver().equals(userId)){
                message.setMessageReadFlag(true);
            }
        });
        // 更新redis中的数据
        redisCache.deleteObject("pet:view:dialogue:" + dialogueId);
        if (!messageList.isEmpty()){
            redisCache.setCacheList("pet:view:dialogue:" + dialogueId,messageList);
        }
        return ResultResponse.ok(messageList);
    }
}
